$(function () {
    $("#username").focus(function () {
        $("#unm_tips").html("");
    });
    $("#username").blur(function () {
        if ($("#username").val() == "")
            $("#unm_tips").html("请输入用户名");
    });
    $("#password").focus(function () {
        $("#psd_tips").html("");
    });
    $("#password").blur(function () {
        if ($("#password").val() == "")
            $("#psd_tips").html("请输入密码");
    });
    $("#codeipt").focus(function () {
        $("#code_tips").html("");
    });
    $("#codeipt").blur(function () {
        if ($("#codeipt").val() == "")
            $("#code_tips").html("请输入验证码");
        else {
            let regex = new RegExp("^[a-zA-z0-9]{4}$");
            let code = $("#codeipt").val();
            if (regex.test(code))
                $("#code_tips").html("");
            else
                $("#code_tips").html("请输入4位有效验证码");
        }
    });
});
//刷新验证码
function flushCode() {
    $("#codeimg").attr("src", "/code?date=" + new Date());
}

//用户登录
function login() {
    //获取登录数据
    let username = $("#username").val();
    let password = $("#password").val();
    let iptcode = $("#codeipt").val();
    console.log(iptcode);
    if (username != "" && password != "" && iptcode != "") {
        //将数据转发给后台
        $.ajax({
            url: "/back/login",
            type: "post",
            data: {
                "username": username,
                "password": password,
                "codeipt": iptcode
            },
            dataType: 'json',
            success: function (data) {
                console.log(data);
                if (data == 1) {
                    alert("登录成功");
                    sessionStorage.setItem("username", username);
                    console.log(sessionStorage.setItem("username", username));
                    window.location.href = "/back/manager";
                } else if (data == 0) {
                    $("#tips").html("登录信息输入错误，请重新输入");
                    flushCode();
                } else {
                    $("#tips").html("验证码输入错误，请重新输入");
                    flushCode();
                }
            },
            error: function (data) {
                console.log(data);
            }
        })
    }
}